package com.tencent.wxcloudrun.service.impl;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tencent.wxcloudrun.constant.RedisKeyConstant;
import com.tencent.wxcloudrun.domain.TUser;
import com.tencent.wxcloudrun.enums.UserStatEnum;
import com.tencent.wxcloudrun.enums.UserTypeEnum;
import com.tencent.wxcloudrun.exception.BusinessException;
import com.tencent.wxcloudrun.mapper.TUserMapper;
import com.tencent.wxcloudrun.service.TUserService;
import com.tencent.wxcloudrun.util.RedisBusiUtil;
import com.tencent.wxcloudrun.util.RedisUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author ziyin.zhao
 * @description 针对表【t_user(用户表)】的数据库操作Service实现
 * @createDate 2025-04-22 16:43:56
 */
@Slf4j
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements TUserService {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public TUser query(Long userId, String wxOpenId) {
        TUser user = new TUser();
        if (userId != null) {
            user = RedisBusiUtil.getUserInfo(userId);
            if (Objects.nonNull(user)) {
                return user;
            }
            user = this.getById(userId);
            if (Objects.nonNull(user)) {
                RedisBusiUtil.saveUserInfo(user);
            }
        } else if (StringUtils.hasLength(wxOpenId)) {
            user = RedisBusiUtil.getUserInfoByWxOpenId(wxOpenId);
            if (Objects.nonNull(user)) {
                return user;
            }
            LambdaQueryWrapper<TUser> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(TUser::getWxOpenId, wxOpenId);
            queryWrapper.eq(TUser::getEnableFlag, 1);
            user = this.getOne(queryWrapper);
            if (Objects.nonNull(user)) {
                RedisBusiUtil.saveUserInfo(user);
            }
        }
        return user;
    }

    @Override
    public TUser addDefUser(String wxOpenId) {
        TUser user = new TUser();
        user.setWxOpenId(wxOpenId);
        user.setStatus(UserStatEnum.NORMAL.getValue());
        user.setType(UserTypeEnum.PLAYER.getValue());
        user.setCreatedTime(LocalDateTime.now());
        user.setUpdatedTime(LocalDateTime.now());
        this.save(user);
        return user;
    }

    @Override
    public void checkAdmin(Long userId) {
        TUser user = this.getById(userId);
        if (Objects.isNull(user)) {
            log.error("人员校验-用户不存在-用户ID={}", userId);
            throw new BusinessException("用户不存在");
        }
        if (UserTypeEnum.ADMIN.getValue() != user.getType()) {
            log.error("人员校验-非管理员操作-拒绝访问-用户ID={}", userId);
            throw new BusinessException("您不是管理员，拒绝访问");
        }
    }

    /**
     * @Author: ZhaoZiYin
     * @Date: 2025/4/27
     * @Params: [user]
     * @Return: void
     * @Description: 保存缓存
     */
    @Override
    public void saveRedis(TUser user) {
        String key = RedisKeyConstant.getUserRedisKey(user.getId());
        String value = JSONObject.toJSONString(user);
        redisUtil.set(key, value);
    }

    @Override
    public List<Long> searchByName(String keyWord) {
        LambdaQueryWrapper<TUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(TUser::getName, keyWord);
        List<TUser> userList = this.list(queryWrapper);
        if (!CollectionUtils.isEmpty(userList)) {
            return userList.stream().map(TUser::getId).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
}
